package auto.app.controller;


import auto.app.controller.from.AutoCollectionResultPage;
import auto.app.exetion.MainExection;
import auto.app.model.AutoCollectionResult;
import auto.app.model.AutoFileInfo;
import auto.app.service.AutoCollectionResultService;
import auto.app.service.AutoFileInfoService;
import auto.app.util.OSSTemplate;
import auto.app.util.ObjectNull;
import auto.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import static auto.app.exetion.MainExetionMessage.AUTOCOLLECTIOONRESULETERROR;
import static auto.app.exetion.MainExetionMessage.FILEAUTOERROR;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 杨森
 * @since 2023-01-30
 */
@RestController
@RequestMapping("/autoCollectionResult")
@Api(value = "测试合集执行结果",tags = "测试合集执行结果")
public class AutoCollectionResultController {

    @Autowired
    private AutoCollectionResultService autoCollectionResultService;

    @Autowired
    private OSSTemplate ossTemplate;

    @Autowired
    private AutoFileInfoService autoFileInfoService;

    @PostMapping(value = "/list",name = "测试合集执行结果分页")
    @ApiOperation(value = "测试合集执行结果分页",notes = "测试合集执行结果分页")
    public Result<AutoCollectionResultPage> list(@Valid @RequestBody AutoCollectionResultPage autoCollectionResultPage) throws MainExection {
        AutoCollectionResultPage list = autoCollectionResultService.list(autoCollectionResultPage);
        return Result.getInstance(AutoCollectionResultPage.class).setData(list);
    }


    @GetMapping(value = "/download/{id}",name = "下载执行结果")
    @ApiOperation(value = "测试执行结果下载",notes = "测试执行结果下载")
    public void export(@PathVariable String id, HttpServletResponse response) throws Exception {
        AutoCollectionResult autoCollectionResultServiceById = autoCollectionResultService.getById(id);
        if (ObjectNull.isNull(autoCollectionResultServiceById)){
            throw new MainExection(AUTOCOLLECTIOONRESULETERROR.getCode(),AUTOCOLLECTIOONRESULETERROR.getMsg());
        }
        LambdaQueryWrapper<AutoFileInfo> autoFileInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AutoFileInfo> autoFileInfoLambdaQueryWrapper1 = autoFileInfoLambdaQueryWrapper.eq(AutoFileInfo::getDataId,id)
                .orderByDesc(AutoFileInfo::getCreateTime)
                .last("limit 1");
        AutoFileInfo autoFileInfoServiceOne = autoFileInfoService.getOne(autoFileInfoLambdaQueryWrapper1);
        if (ObjectNull.isNull(autoFileInfoServiceOne)){
            throw new MainExection(FILEAUTOERROR.getCode(),FILEAUTOERROR.getMsg());
        }
        ossTemplate.downloadFile(autoFileInfoServiceOne.getFileName(),autoFileInfoServiceOne.getOriginalFileName(),response);
    }


}

